package com.tjjingpan.wifidirectdemo

import android.Manifest
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.NetworkInfo
import android.net.wifi.p2p.*
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.permissionx.guolindev.PermissionX
import com.tjjingpan.wifidirectdemo.callback.DirectActionListener
import com.tjjingpan.wifidirectdemo.utils.WifiDirectManager
import kotlinx.android.synthetic.main.activity_main.*
import android.net.wifi.p2p.WifiP2pDevice
import androidx.recyclerview.widget.LinearLayoutManager
import com.tjjingpan.wifidirectdemo.test.Fruit
import com.tjjingpan.wifidirectdemo.test.FruitAdapter
import kotlin.concurrent.thread


class MainActivity : AppCompatActivity(){
    override fun onDestroy() {
        super.onDestroy()
        //unregisterReceiver(wifiDirectReceiver)
    }
    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initWifiDireManager()
        initReceiver()


//        val layoutManager = LinearLayoutManager(this)
//        rvwifidevices.layoutManager = layoutManager
//        rvwifidevices.adapter= WifiDirectManager.rvadapter

//        val layoutManager = LinearLayoutManager(this)
//        rvwifidevices.layoutManager = layoutManager
//        val adapter = FruitAdapter(fruitList)
//        rvwifidevices.adapter = adapter
//
//        val layoutManager = LinearLayoutManager(this)
//        rvwifidevices.layoutManager = layoutManager
//        rvwifidevices.adapter= WifiDirectManager.adapter



        val layoutManager = LinearLayoutManager(this)
        rvwifidevices.layoutManager = layoutManager
        rvwifidevices.adapter= WifiDirectManager.deviceAdapter


        btnCheckPermission.setOnClickListener {
         PermissionX.init(this)
             .permissions(Manifest.permission.INTERNET,
                 Manifest.permission.ACCESS_FINE_LOCATION,
                 Manifest.permission.ACCESS_COARSE_LOCATION,
                 Manifest.permission.ACCESS_NETWORK_STATE,
                 Manifest.permission.CHANGE_NETWORK_STATE,
                 Manifest.permission.ACCESS_WIFI_STATE,
                 Manifest.permission.CHANGE_WIFI_STATE,
                 Manifest.permission.READ_EXTERNAL_STORAGE,
                 Manifest.permission.WRITE_EXTERNAL_STORAGE)
             .request{ allGranted,grantedList,deniedList ->
                 if(allGranted){
                     Toast.makeText(this,"All permissions are granted",Toast.LENGTH_SHORT).show()
                 }
                 else{
                     Toast.makeText(this,"these permissions are denied:$deniedList",Toast.LENGTH_SHORT).show()
                 }
             }
        }


       btnCreateGroup.setOnClickListener {
           WifiDirectManager.createGroup()
       }
        btnRemoveGroup.setOnClickListener {
            WifiDirectManager.removeGroup()
        }
        btnDiscoverPeer.setOnClickListener {
            //WifiDirectManager.discoverPeers()
            //initFruits()
            //adapter.notifyDataSetChanged()
            //btnDiscoverPeer.isEnabled=false
            //btnDiscoverPeer.text = "正在搜索设备"

            thread {
                WifiDirectManager.discoverPeers()
                runOnUiThread{
                    btnDiscoverPeer.isEnabled=false
                    btnDiscoverPeer.text = "正在扫描设备"
                }

            }
        }
        btnStopDiscoverPeer.setOnClickListener {
            btnDiscoverPeer.isEnabled=true
            btnDiscoverPeer.text = "扫描"
        }

    }

    inner class WifiDirectReceiver(val wifiP2pManager: WifiP2pManager,
                                   val channel:WifiP2pManager.Channel,
                                   val directActionListener: DirectActionListener
    ) : BroadcastReceiver(){
        val TAG = "WifiDirectReceiver"
        /**
         * 写一个便捷的注册方法，动态注册的时候就不用写initerFilter了
         */
        fun registerReceiver(context: Context){
            val intentFilter = IntentFilter()
            intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)
            intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)
            intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)
            intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)
            context.registerReceiver(this,intentFilter)
        }
        @SuppressLint("MissingPermission", "NotifyDataSetChanged")
        override fun onReceive(context: Context?, intent: Intent?) {
            when(intent?.action){
                /**
                 * 当wifi功能打开或关闭时候系统会发送WIFI_P2P_STATE_CHANGED_ACTION广播
                 * 并不是指是否已成功连上wifi
                 * 用于指示wifi p2p是否可用
                 */
                WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION ->{
                    //get the state of current device
                    val state = intent.getIntExtra(
                        WifiP2pManager.EXTRA_WIFI_STATE,
                        WifiP2pManager.WIFI_P2P_STATE_DISABLED)
                    if(state == WifiP2pManager.WIFI_P2P_STATE_ENABLED){

                        //wifi p2p enable
                        Log.d(TAG,"wifi enable")
                        directActionListener.wifiP2pEnabled(true)
                    }
                    else{
                        //wifi p2p disEnable
                        Log.d(TAG,"wifi disable")
                        directActionListener.wifiP2pEnabled(false)
                    }
                }
                /**
                 * 当前设备的详细信息发生变化的时候，系统会发送WIFI_P2P_THIS_DEVICE_CHANGED_ACTION广播
                 */
                WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION ->{
                    val device : WifiP2pDevice? = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)
                    Log.d(TAG,device.toString())

                }
                /**
                 * 当可连接的对等节点列表发生改变的时候，会发送该广播
                 * invoke when the list of peers find,register,lost
                 */
                WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION ->{
                    wifiP2pManager.requestPeers(channel) { peers ->
                            directActionListener.onPeersAvailable(
                                peers.deviceList
                            )
                        }
                    btnDiscoverPeer.isEnabled = true
                    btnDiscoverPeer.text = "扫描"
                    //api > 18 have this extra info,
//                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
//                        val wifiP2pList: WifiP2pDeviceList? = intent.getParcelableExtra(
//                            WifiP2pManager.EXTRA_P2P_DEVICE_LIST)
//                        Log.d(TAG,wifiP2pList.toString())
//
//                        WifiDirectManager.wifiP2pDeviceList = wifiP2pList?.deviceList
//                        Log.d(TAG, "wifidevice数量:"+ WifiDirectManager.wifiP2pDeviceList?.size.toString())
//
//                        for (device in WifiDirectManager.wifiP2pDeviceList!!){
//                            Log.d(TAG,"设备的名字${device.deviceName},设备的地址${device.deviceAddress}" +
//                                    "是否是组创建者${device.isGroupOwner},设备的状态${device.status}")
//                            WifiDirectManager.peersshowlist?.add(device)
//                        }
//
//                        wifiP2pManager.requestPeers(channel) { peers ->
//                            directActionListener.onPeersAvailable(
//                                peers.deviceList
//                            )
//                        }
//                        adapter.notifyDataSetChanged()
//                    }else{ //if ths sdk version lower than 18
//                        //get wifiP2pDeviceList by call WifiP2pManager.requestPeers to get
//                        WifiDirectManager.requestPeers()
//                    }
                }
                /**
                 * 当一个连接建立或断开的时候，系统会发送该广播
                 * This action received when connection setup or dis-setup
                 */
                WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION ->{
                    val networkInfo = intent.getParcelableExtra<NetworkInfo>(WifiP2pManager.EXTRA_NETWORK_INFO)
                    val wifiP2pInfo = intent.getParcelableExtra<WifiP2pInfo>(WifiP2pManager.EXTRA_WIFI_P2P_INFO)

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                        val wifiP2pGroupInfo =  intent.getParcelableExtra<WifiP2pGroup>(WifiP2pManager.EXTRA_WIFI_P2P_GROUP)
                    } else {

                    }
                }
            }
        }
    }

    private fun initWifiDireManager(){
        WifiDirectManager.init(this)
    }
    private fun initReceiver(){
        val wifiDirectReceiver = WifiDirectReceiver(WifiDirectManager.manager,
            WifiDirectManager.channel,
            WifiDirectManager.directActionListener)
        wifiDirectReceiver.registerReceiver(this)
    }

    private val fruitList = ArrayList<Fruit>()
    private fun initFruits() {
        repeat(2) {
            fruitList.add(Fruit("Apple", R.drawable.apple_pic))
            fruitList.add(Fruit("Banana", R.drawable.banana_pic))
            fruitList.add(Fruit("Orange", R.drawable.orange_pic))
            fruitList.add(Fruit("Watermelon", R.drawable.watermelon_pic))
            fruitList.add(Fruit("Pear", R.drawable.pear_pic))
            fruitList.add(Fruit("Grape", R.drawable.grape_pic))
            fruitList.add(Fruit("Pineapple", R.drawable.pineapple_pic))
            fruitList.add(Fruit("Strawberry", R.drawable.strawberry_pic))
            fruitList.add(Fruit("Cherry", R.drawable.cherry_pic))
            fruitList.add(Fruit("Mango", R.drawable.mango_pic))
        }
    }
}